<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义new和instanceof</title>
</head>

<body>

  <script>
    function newInstance(Type, ...args) {
      // 1. 创建一个空的Object实例对象
      const obj = {}
      // 2. 调用构造函数, 并指定this为新创建的对象
      const result = Type.call(obj, ...args)
      if (result instanceof Object) return result
      // 3. 给对象添加__proto__属性, 值为构造函数的prototype
      obj.__proto__ = Type.prototype
      // 4. 返回对象
      return obj
    }

    /* 
    Type的prototype指向的是否是obj原型链上的某个对象
    */
    function myInstanceOf(obj, Type) {
      let protoObj = obj.__proto__
      while(protoObj) {
        if (Type.prototype===protoObj) return true

        protoObj = protoObj.__proto__
      }

      return false
    }
  </script>

  <script>


    function Person(name, age) {
      this.name = name
      this.age = age
      // return this
      // return 1
      // return () => {}
      // return []
      // return {}
    }

    const p = new Person('tom', 12)
    console.log(p);

    const p2 = newInstance(Person, 'Jack', 13)
    console.log(p2)

    console.log(myInstanceOf(p, Person))
    console.log(myInstanceOf(p, Object))
    console.log(myInstanceOf(p, Function))
 
  </script>
</body>

</html>